/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Telas;

import DAO.*;
import java.sql.*;

import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import models.Emprestimo;
import sun.util.calendar.LocalGregorianCalendar.Date;

/**
 *
 * @author Maria Sophia
 */
public class CEmprestimo extends javax.swing.JFrame {

    /**
     * Creates new form Livro
     */
    public CEmprestimo() {

        initComponents();
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        java.util.Date data = new java.util.Date();
        data.setDate(data.getDate());
        String ret = format.format(data);
        retirada.setText(ret);

        data.setDate(data.getDate() + 5);
        String previst = format.format(data);
        prevista.setText(previst);


    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        biblionlinePUEntityManager0 = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("biblionlinePU").createEntityManager();
        clienteQuery = java.beans.Beans.isDesignTime() ? null : biblionlinePUEntityManager0.createQuery("SELECT c FROM Cliente c");
        clienteList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : clienteQuery.getResultList();
        jSeparator5 = new javax.swing.JSeparator();
        jLabel1 = new javax.swing.JLabel();
        novo = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();
        jSeparator1 = new javax.swing.JSeparator();
        alterar = new javax.swing.JButton();
        sair = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        cod = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        cli = new javax.swing.JTextField();
        liv = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        rescliente = new javax.swing.JLabel();
        reslivro = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        retirada = new javax.swing.JLabel();
        prevista = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
        getContentPane().add(jSeparator5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 103, 574, 7));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel1.setText("Emprestimo");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(222, 68, -1, -1));

        novo.setBackground(new java.awt.Color(153, 153, 153));
        novo.setFont(new java.awt.Font("Kristen ITC", 1, 18)); // NOI18N
        novo.setForeground(new java.awt.Color(0, 51, 255));
        novo.setText("Novo");
        novo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                novoActionPerformed(evt);
            }
        });
        getContentPane().add(novo, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 369, 139, -1));

        jLabel2.setBackground(new java.awt.Color(204, 204, 204));
        jLabel2.setFont(new java.awt.Font("Kristen ITC", 1, 24)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(0, 0, 204));
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("Gerenciador de Bibliotecas - BibliOnline");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(48, 18, -1, -1));
        getContentPane().add(jSeparator2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 57, 574, 8));
        getContentPane().add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, 574, -1));

        alterar.setBackground(new java.awt.Color(153, 153, 153));
        alterar.setFont(new java.awt.Font("Kristen ITC", 1, 18)); // NOI18N
        alterar.setForeground(new java.awt.Color(0, 51, 255));
        alterar.setText("Incluir");
        alterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                alterarActionPerformed(evt);
            }
        });
        getContentPane().add(alterar, new org.netbeans.lib.awtextra.AbsoluteConstraints(155, 369, 139, -1));

        sair.setBackground(new java.awt.Color(153, 153, 153));
        sair.setFont(new java.awt.Font("Kristen ITC", 1, 18)); // NOI18N
        sair.setForeground(new java.awt.Color(0, 51, 255));
        sair.setText("Sair");
        sair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sairActionPerformed(evt);
            }
        });
        getContentPane().add(sair, new org.netbeans.lib.awtextra.AbsoluteConstraints(453, 369, 139, -1));

        jLabel3.setText("Pedido");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 121, -1, -1));

        cod.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                codActionPerformed(evt);
            }
        });
        getContentPane().add(cod, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 140, 111, -1));

        jLabel4.setText("Codigo Cliente");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 166, -1, -1));

        cli.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cliActionPerformed(evt);
            }
        });
        getContentPane().add(cli, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 186, 65, -1));

        liv.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                livActionPerformed(evt);
            }
        });
        getContentPane().add(liv, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 232, 65, -1));

        jLabel12.setText("Codigo Livro");
        getContentPane().add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 212, -1, -1));
        getContentPane().add(rescliente, new org.netbeans.lib.awtextra.AbsoluteConstraints(79, 186, 360, 20));
        getContentPane().add(reslivro, new org.netbeans.lib.awtextra.AbsoluteConstraints(79, 232, 360, 20));

        jLabel5.setText("Data Retirada");
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(453, 121, -1, -1));
        getContentPane().add(retirada, new org.netbeans.lib.awtextra.AbsoluteConstraints(453, 140, 139, 20));
        getContentPane().add(prevista, new org.netbeans.lib.awtextra.AbsoluteConstraints(453, 186, 139, 20));

        jLabel6.setText("Data Prevista");
        getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(453, 166, -1, -1));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void sairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sairActionPerformed
        dispose();
    }//GEN-LAST:event_sairActionPerformed

    private void alterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_alterarActionPerformed
        try {
            try (Connection conn = FabricaConexao.getConnection()) {
                Statement st = conn.createStatement();
                ResultSet rs1 = st.executeQuery("select * from livro where registro='" + liv.getText() + "';");
                while (rs1.next()) {
                    if (rs1.getInt(4) > 0) {
                        int novoestoque = rs1.getInt(4) - 1;
                        String sql = "UPDATE `biblionline`.`livro` SET `estoque1` = '" + novoestoque + "' WHERE `livro`.`registro` = '" + liv.getText() + "';";

                        try {
                            EmprestimoJDBC emprestimojdbc = new EmprestimoJDBC();
                            Emprestimo emp = new Emprestimo();


                            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
                            java.util.Date data = new java.util.Date();
                            data.setDate(data.getDate());
                            String ret = format.format(data);

                            data.setDate(data.getDate() + 5);
                            String previst = format.format(data);

                            emp.setCodcliente(Integer.parseInt(cli.getText()));
                            emp.setCodlivro(Integer.parseInt(liv.getText()));

                            emp.setDataretirada(ret);
                            emp.setDataprevista(previst);

                            emprestimojdbc.inserir(emp);

                            cli.setText("");
                            liv.setText("");

                            JOptionPane.showMessageDialog(null, "Adicionado com Sucesso!!");
                        } catch (DAOException ex) {
                            Logger.getLogger(CEmprestimo.class.getName()).log(Level.SEVERE, null, ex);
                            JOptionPane.showMessageDialog(null, "Erro ao adicionar!!");

                        }

                        st.executeUpdate(sql);
                    } else {
                        JOptionPane.showMessageDialog(null, "Não pode Emprestar por que não consta no estoque!!");
                    }
                }
            }

        } catch (ErroConexao | SQLException ex) {
            try {
                throw new DAOException(ex);
            } catch (DAOException ex1) {
                Logger.getLogger(Renovar.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }


    }//GEN-LAST:event_alterarActionPerformed

    private void novoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_novoActionPerformed
        dispose();
        CEmprestimo emprestimo = new CEmprestimo();
        emprestimo.setVisible(true);
    }//GEN-LAST:event_novoActionPerformed

    private void cliActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cliActionPerformed
        try {
            Connection c1 = DriverManager.getConnection("jdbc:mysql://localhost/biblionline", "root", "");
            Statement st1 = c1.createStatement();
            ResultSet rs1 = st1.executeQuery("select * from cliente where cod='" + cli.getText() + "';");
            while (rs1.next()) {
                if (cli.getText() == rs1.getString(1)) {
                    rescliente.setText(rs1.getString(2));

                } else {
                    rescliente.setText(rs1.getString(2));
                }
            }
            c1.close();
        } catch (SQLException ex) {
            Logger.getLogger(CEmprestimo.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_cliActionPerformed

    private void livActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_livActionPerformed
        try {
            Connection c2 = DriverManager.getConnection("jdbc:mysql://localhost/biblionline", "root", "");
            Statement st2 = c2.createStatement();
            ResultSet rs2 = st2.executeQuery("select * from livro where registro='" + liv.getText() + "';");
            while (rs2.next()) {
                if (liv.getText() == rs2.getString(1)) {
                    reslivro.setText(rs2.getString(2));

                } else {
                    reslivro.setText(rs2.getString(2));
                }
            }
            c2.close();
        } catch (SQLException ex) {
            Logger.getLogger(CEmprestimo.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_livActionPerformed

    private void codActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_codActionPerformed
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection c = DriverManager.getConnection("jdbc:mysql://localhost/biblionline", "root", "");
            Statement st = c.createStatement();
            ResultSet rs = st.executeQuery("select * from emprestimo where cod='" + cod.getText() + "';");
            while (rs.next()) {
                cli.setText(rs.getString(6));
                liv.setText(rs.getString(5));
                retirada.setText(rs.getString(2));
                prevista.setText(rs.getString(3));
            }
            c.close();
            Connection c1 = DriverManager.getConnection("jdbc:mysql://localhost/biblionline", "root", "");
            Statement st1 = c1.createStatement();
            ResultSet rs1 = st1.executeQuery("select * from cliente where cod='" + cli.getText() + "';");
            while (rs1.next()) {
                if (cli.getText() == rs1.getString(1)) {
                    rescliente.setText(rs1.getString(2));

                } else {
                    rescliente.setText(rs1.getString(2));
                }
            }
            c1.close();
            Connection c2 = DriverManager.getConnection("jdbc:mysql://localhost/biblionline", "root", "");
            Statement st2 = c2.createStatement();
            ResultSet rs2 = st2.executeQuery("select * from livro where registro='" + liv.getText() + "';");
            while (rs2.next()) {
                if (liv.getText() == rs2.getString(1)) {
                    reslivro.setText(rs2.getString(2));

                } else {
                    reslivro.setText(rs2.getString(2));
                }
            }
            c2.close();



        } catch (ClassNotFoundException e) {
            System.out.println("erro no driver");
        } catch (SQLException e) {
            System.out.println("erro no banco");
            System.out.println(e.getMessage());
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_codActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CEmprestimo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CEmprestimo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CEmprestimo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CEmprestimo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new CEmprestimo().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton alterar;
    private javax.persistence.EntityManager biblionlinePUEntityManager0;
    private javax.swing.JTextField cli;
    private java.util.List<Telas.Cliente> clienteList;
    private javax.persistence.Query clienteQuery;
    private javax.swing.JTextField cod;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator5;
    private javax.swing.JTextField liv;
    private javax.swing.JButton novo;
    private javax.swing.JLabel prevista;
    private javax.swing.JLabel rescliente;
    private javax.swing.JLabel reslivro;
    private javax.swing.JLabel retirada;
    private javax.swing.JButton sair;
    // End of variables declaration//GEN-END:variables
}
